תוכנה 1 3 תרגול מס' מערכים ומבני בקרה

Similar documents
תוכנה 1 מערכים. Array Creation and Initialization. Array Declaration. Array Creation and Initialization. Loop through Arrays

תוכנה 1 מערכים. Array Creation and Initialization. Array Declaration. Loop through Arrays. Array Creation and Initialization

תוכנה 1 תרגול 2: מערכים ומבני בקרה

הנכות 1 תואיגש םע תודדומתהו תואלול,םיכרעמ : לו 2 גרת

תוכנה 1 תרגול 2: מערכים, מבני בקרה ושגיאות

הנכות 1 תואיגש םע תודדומתהו תואלול,םי : כרעמ 2 לוגרת

Ohad Barzilay and Oranit Dror

Sun שיטת הגמל: "isodd" "is_odd" Sun. תוכנה 1 בשפת Java אוניברסיטת תל אביב

תוכנה 1. תרגול מספר 11: Static vs. Dynamic Binding מחלקות מקוננות Nested Classes

CS Programming I: Arrays

תוכנה 1 סמסטר א' תשע"א

Java Programming Language Mr.Rungrote Phonkam

מבוא לתכנות ב- JAVA תרגול 7

מערכים שעור מס. 4 כל הזכויות שמורות דר ' דרור טובי המרכז האוניברסיטאי אריאל 1

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values

Recursion Enums. Basics of Programming 1. Department of Networked Systems and Services G. Horváth, A.B. Nagy, Z. Zsóka, P. Fiala, A.

CMIS 102 Hands-On Lab

Array. Array Declaration:

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

הנכות 1 םוכיס לוגרת 14 1

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

Syntax and Variables

Asks for clarification of whether a GOP must communicate to a TOP that a generator is in manual mode (no AVR) during start up or shut down.

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Exam 2 ITEC 120 Principles of Computer Science I Spring: 2017

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

All King County Summary Report

CS1 Recitation. Week 2

High Performance Computing

This report is based on sampled data. Jun 1 Jul 6 Aug 10 Sep 14 Oct 19 Nov 23 Dec 28 Feb 1 Mar 8 Apr 12 May 17 Ju

Answers to review questions from Chapter 2

Seattle (NWMLS Areas: 140, 380, 385, 390, 700, 701, 705, 710) Summary

Seattle (NWMLS Areas: 140, 380, 385, 390, 700, 701, 705, 710) Summary

Recursion. Fundamentals of Computer Science

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Seattle (NWMLS Areas: 140, 380, 385, 390, 700, 701, 705, 710) Summary

תור שימושים בעולם התוכנה

C Structures, Unions, Bit Manipulations, and Enumerations

מחרוזות ב Java ותכנות מונחה בדיקות )Test Driven Development(

More Binary Search Trees AVL Trees. CS300 Data Structures (Fall 2013)

History. used in early Mac development notable systems in Pascal Skype TeX embedded systems

More BSTs & AVL Trees bstdelete

Arrays III and Enumerated Types

Pace University. Fundamental Concepts of CS121 1

software.sci.utah.edu (Select Visitors)

CSI33 Data Structures

סכום (סדרת ערכים) אחרת - דוגמא: סכום-ספרות (num) אם < 10 num החזר 1 או אם = 0 = num החזר 0 public static int numofdigits (int num)

Undergraduate Admission File

Arrays. CSE 142, Summer 2002 Computer Programming 1.

ECSE 321 Assignment 2

Getting started with Java

i.e.: n! = n (n 1)

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

recursive algorithms 1

Section 1.2: What is a Function? y = 4x

הקלחמ ה תמרב ת ונ וכ ת (static members ) יליזרב דהוא Java תפשב ם דקת מ תונכת ביבא ל ת תטיסרבינוא

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Recursion. General Algorithm for Recursion. When to use and not use Recursion. Recursion Removal. Examples

Type Definition. C Types. Derived. Function Array Pointer Structure Union Enumerated. EE 1910 Winter 2017/18

CS/COE 1501

Introduction. Structures, Unions, Bit Manipulations, and Enumerations. Structure. Structure Definitions

Programming for Engineers Structures, Unions

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

מצליחה. 1. int fork-bomb() 2. { 3. fork(); 4. fork() && fork() fork(); 5. fork(); printf("bla\n"); 8. return 0; 9. }

Data Structures and Algorithms (DSA) Course 4. Iulian Năstac

CSE 341 Section Handout #6 Cheat Sheet

HPE Security Data Security. HPE SecureData. Product Lifecycle Status. End of Support Dates. Date: April 20, 2017 Version:

OBJECT ORIENTED PROGRAMMING USING C++

Characterization and Modeling of Deleted Questions on Stack Overflow

Unit #2: Recursion, Induction, and Loop Invariants

Lecture 16. Reading: Weiss Ch. 5 CSE 100, UCSD: LEC 16. Page 1 of 40

Question 2. [5 points] State a big-o upper bound on the worst case running time of the given

Opera Web Browser Archive - FTP Site Statistics. Top 20 Directories Sorted by Disk Space

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Unit #3: Recursion, Induction, and Loop Invariants

Recursive Definitions

Statistical Charts and Graphs. June 1, 2012

Lecture Notes: ESC 101

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

מבוא לתכנות ב- JAVA תרגול 6

Complexity of Algorithms

Object-Oriented Programming in Java. Topic : Objects and Classes (cont) Object Oriented Design

School of Informatics, University of Edinburgh

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Scientific Programming in C X. More features & Fortran interface

Data Types H&K Chapter 7. Instructor - Andrew S. O Fallon CptS 121 (October 17, 2018) Washington State University

CS 455 Midterm Exam 1 Spring 2013 [Bono] Feb. 21, 2013

ICT PROFESSIONAL MICROSOFT OFFICE SCHEDULE MIDRAND

Objectives of the lesson

Omega Engineering Software Archive - FTP Site Statistics. Top 20 Directories Sorted by Disk Space

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Lecture 14. Dynamic Memory Allocation

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Transcription:

תוכנה 1 3 תרגול מס' מערכים ומבני בקרה

מערכים Array: A fixed-length data structure for storing multiple values of the same type Example: An array of odd numbers: Indices (start from 0) 0 1 2 3 4 5 6 7 odds: 1 3 5 7 9 11 13 15 The type of all elements is int odds.length == 8 The value of the element at index 4 is 9: odds[4] == 9 2

Array Declaration An array is denoted by the [] notation Examples: int[] odds; int odds[]; // legal but discouraged String[] names; int[][] matrix; // an array of arrays matrix: 3

Array Creation and Initialization What is the output of the following code: int[] odds = new int[8]; for (int i = 0; i < odds.length; i++) { System.out.print(odds[i] + " "); odds[i] = 2 * i + 1; System.out.print(odds[i] + " "); Output: Array creation: all elements get the default value for their type (0 for int) 0 1 0 3 0 5 0 7 0 9 0 11 0 13 0 15 4

Array Creation and Initialization Creating and initializing small arrays with a-priori known values: int[] odds = {1,3,5,7,9,11,13,15; String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"; Jan months: 5

Loop through Arrays By promoting the array's index: for (int i = 0; i < months.length; i++) { System.out.println(months[i]); foreach (since Java 5.0): for (String month: months) { System.out.println(month); The variable month is assigned the next element in each iteration 6

Copying Arrays Assume: int[] array1 = {1,2,3; int[] array2 = {8,7,6,5; Naïve copy: array1 = array2; 8,7,6,5 array2 1,2,3 array1 How would we copy an array? 8

Copying Arrays Arrays.copyOf the original array the length of the copy int[] arr1 = {1, 2, 3; int[] arr2 = Arrays.copyOf(arr1, arr1.length); Arrays.copyOfRange the original array initial index of the range to be copied, inclusive final index of the range to be copied, exclusive See also: System.arraycopy 9

What is the output of the following code: int[] odds = {1, 3, 5, 7, 9, 11, 13, 15; int[] newodds = Arrays.copyOfRange(odds, 1, odds.length); for (int odd: newodds) { System.out.print(odd + " "); Output: 3 5 7 9 11 13 15 10

Other Manipulations on Arrays The java.util.arrays class has methods for sorting and searching, assigning arrays e.g. public static void sort(int[] a) public static int binarysearch(int[] a, int key) public static void fill(long[] a, long val) More details in JDK 6.0 documentation http://java.sun.com/javase/6/docs/api/java/util/arrays.html 11

2D Arrays There are no 2D arrays in Java but you can build array of arrays: char[][] board = new char[3][]; for (int i = 0; i < 3; i++) board[i] = new char[3]; Or equivalently: char[][] board = new char[3][3]; board 12

2D Arrays Building a multiplication table: int[][] table = new int[10][10]; for (int i = 0 ;i < 10 ;i++) { for (int j = 0 ;j < 10; j++) { table[i][j] = (i+1) * (j+1); 13

Fibonacci Fibonacci series: 1, 1, 2, 3, 5, 8, 13, 21, 34 Definition: fib(0) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) en.wikipedia.org/wiki/fibonacci_number

סלט פיבונאצ'י

If-Else Statement public class Fibonacci { /** Returns the n-th Fibonacci element */ public static int computeelement(int n) { if (n==0) return 1; else if (n==1) return 1; else return computeelement(n-1) + computeelement(n-2); Can be removed Assumption: n 0 16

Switch Statement public class Fibonacci { /** Returns the n-th Fibonacci element */ public static int computeelement(int n) { switch(n) { case 0: return 1; case 1: return 1; default: Assumption: n 0 can be placed outside the switch return computeelement(n-1) + computeelement(n-2); 17

Switch Statement public class Fibonacci { /** Returns the n-th Fibonacci element */ public static int computeelement(int n) { switch(n) { case 0: return 1; case 1: return 1; break; default: Compilation Error: Dead Code Assumption: n 0 return computeelement(n-1) + computeelement(n-2); 18

For Loop A loop instead of a recursion static int computeelement(int n) { if (n == 0 n == 1) return 1; int prev = 1; int prevprev = 1; int curr; Assumption: n 0 for (int i = 2 ; i < n ; i++) { curr = prev + prevprev; prevprev = prev; prev = curr; curr = prev + prevprev; return curr; 19

נתונים במקום חישוב בתרגום רקורסיה ללולאה אנו משתמשים במשתני עזר לשמירת המצב curr, prev ו- prevprev הלולאה "זוכרת" את הנקודה שבה אנו נמצאים בתהליך החישוב דיון: יעילות לעומת פשטות. עיקרון ה- KISS )keep it simple stupid( תרגיל: כתבו את השירות computeelement בעזרת prev ו- prevprev בלבד )ללא )curr 20

For Loop Printing the first n elements: public class Fibonacci { public static int computeelement(int n) { It is better to use args[0] public static void main(string[] args) { for(int i = 0 ; i < 10 ; i++) System.out.println(computeElement(i)); 21

מודולריות, שכפול קוד ויעילות יש כאן חוסר יעילות מסוים: לולאת ה- for חוזרת גם ב- main וגם ב-.computeElement לכאורה, במעבר אחד ניתן גם לחשב את האברים וגם להדפיס אותם כמו כן כדי לחשב איבר בסדרה איננו משתמשים בתוצאות שכבר חישבנו )של אברים קודמים( ומתחילים כל חישוב מתחילתו 22

מודולריות, שכפול קוד ויעילות צריכה לעשות דבר אחד בדיוק! והדפסה פוגע במודולריות )מדוע?( מתודה )פונקציה( ערוב של חישוב היזהרו משכפול קוד! קטע קוד דומה המופיע בשתי פונקציות שונות יגרום במוקדם או במאוחר לבאג בתוכנית )מדוע?( את בעיית היעילות )הוספת מנגנון )memoization אפשר לפתור בעזרת מערכים )תרגיל( 23

for vs. while The following two statements are almost equivalent: Variable i is not defined outside the for block for(int i = 0 ; i < n ; i++) System.out.println(computeElement(i)); int i=0; while (i < n) { System.out.println(computeElement(i)); i++; 24

while vs. do while The following two statements are equivalent if and only if n>0 : int i=0; while (i < n) { System.out.println(computeElement(i)); i++; works since n 1 int i=0; do { System.out.println(computeElement(i)); i++; while (i>n(; 25

שאלות? הסוף... 26